<template>
  <div class="container1">
    <div class="date-selector">
      <!-- 一级选择：时间类型 -->
      <div class="select-group">
        <el-select
          v-model="timeType"
          style="width: 80px; margin-right: 10px"
          @change="handleTypeChange"
        >
          <el-option label="按年" value="year"></el-option>
          <el-option label="按季" value="quarter"></el-option>
          <el-option label="按月" value="month"></el-option>
          <!-- <el-option label="按周" value="week"></el-option> -->
        </el-select>
      </div>

      <!-- 二级联动选择 -->
      <div class="select-group">
        <div
          style="display: flex; align-items: center; color: #333"
          v-if="timeType === 'year'"
        >
          <el-date-picker
            v-model="startYear"
            type="year"
            value-format="yyyy"
            style="width: 120px"
            placeholder="起始年份"
            :picker-options="pickerOptions"
            @change="handleStartChangeYear"
          >
          </el-date-picker>
          至
          <el-date-picker
            v-model="endYear"
            type="year"
            value-format="yyyy"
            style="width: 120px"
            @change="handleEndChangeYear"
            placeholder="结束年份"
          >
          </el-date-picker>
        </div>
        <div
          style="display: flex; align-items: center"
          v-if="timeType === 'month'"
        >
          <el-date-picker
            v-model="defaultMonthRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            value-format="yyyy-MM"
            style="width: 200px"
            @change="changeSelTime"
          />
        </div>

        <!-- <el-select
          v-model="selectedValue1"
          @change="changeQuarter"
          v-else-if="timeType === 'quarter'"
          style="width: 200px"
        >
          <el-option
            v-for="q in quarters"
            :key="q.value"
            :value="q.value"
            :label="q.label"
          >
          </el-option>
        </el-select> -->

        <el-date-picker
          v-model="selectedValue1"
          type="year"
          value-format="yyyy"
          v-else-if="timeType === 'quarter'"
          placeholder="选择年"
          @change="changeQuarter"
        >
        </el-date-picker>

        <el-select
          v-model="selectedValue2"
          @change="changeWeek"
          v-else-if="timeType === 'week'"
          style="width: 250px"
        >
          <el-option
            v-for="w in weeks"
            :key="w.number"
            :value="w.number"
            :label="w.label"
          >
          </el-option>
        </el-select>
      </div>
    </div>

    <!-- 日期范围展示 -->
    <!-- <div v-if="dateRange.start" class="date-range">
      日期范围：{{ dateRange.start }} 至 {{ dateRange.end }}
    </div> -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      pickerOptions: {
        disabledDate: (time) => {
          const currentYear = new Date().getFullYear();
          const year = time.getFullYear();
          return year > currentYear - 1; // 前年：currentYear -1
        },
      },
      timeType: "month",
      selectedValue: null,
      selectedValue1: new Date().toISOString().split("T")[0],
      selectedValue2: null,
      defaultYearRange: [
        new Date(new Date().getFullYear(), 0, 1), // 当前年第一天
        new Date(new Date().getFullYear(), 11, 31), // 当前年最后一天
      ],

      years: this.generateYears(2020, 2030),
      quarters: this.generateQuarters(),
      weeks: this.generateWeeks(new Date().getFullYear()),
      dateRange: {
        start: "",
        end: "",
        type: 1,
      },

      startYear: new Date().toISOString().split("T")[0],
      endYear: new Date().toISOString().split("T")[0],

      defaultMonthRange: [], // 初始化空数组
    };
  },

  watch: {
    dateRange: {
      handler(val) {
        let type = 0;
        switch (this.timeType) {
          case "year":
            type = 1;
            break;
          case "quarter":
            type = 2;
            break;
          case "month":
            type = 3;
            break;
          case "week":
            type = 4;
            break;
        }

        this.$emit("changeTime", { ...val, type });
      },
      deep: true,
      immediate: true,
    },
  },

  created() {
    this.getMonths();

  },
  mounted() {
    
  },
  methods: {
    changeSelYear() {
      this.dateRange.start = val[0];
      this.dateRange.end = val[1];
    },

    getMonths() {
      // 计算当前时间及一年前的月份
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth() + 1; // 月份从1开始

      // 计算一年前的月份
      const startYear = currentYear - 1;
      const startMonth = currentMonth;

      // 格式化月份（补零）
      const start = `${startYear}-${startMonth.toString().padStart(2, "0")}`;
      const end = `${currentYear}-${currentMonth.toString().padStart(2, "0")}`;

      // 赋值初始区间
      this.defaultMonthRange = [start, end];
      this.dateRange = {
        start: start,
        end: end,
      };
      // this.$emit("changeTime", { ...this.dateRange, type:1 });
    },
    changeSelTime(val) {
      this.dateRange.start = val[0];
      this.dateRange.end = val[1];
    },
    getQuarterDateRange(year = new Date().getFullYear(), quarter) {
      // 参数校验
      if (quarter < 1 || quarter > 4) return null;

      // 计算季度起始月份
      const startMonth = (quarter - 1) * 3;
      const endMonth = startMonth + 2;

      // 生成开始日期（YYYY-MM-DD）
      const startDate = new Date(year, startMonth, 1);
      const formattedStart = `${startDate.getFullYear()}-${(
        startDate.getMonth() + 1
      )
        .toString()
        .padStart(2, "0")}-01`;

      // 计算结束日期（自动处理月末）
      const endDate = new Date(year, endMonth + 1, 0); // 下个月第0天即为本月最后一天
      const formattedEnd = `${endDate.getFullYear()}-${(endDate.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${endDate.getDate().toString().padStart(2, "0")}`;

      return {
        start: formattedStart,
        end: formattedEnd,
      };
    },
    getWeekDateRange(year = new Date().getFullYear(), week) {
      // 参数校验
      if (week < 1 || week > 53) return null;

      // 计算该年份的1月1日
      const date = new Date(year, 0, 1);
      const dayOfWeek = date.getDay(); // 0(周日)到6(周六)

      // 找到第一个周日（若1月1日非周日则向前推算）
      const diffDays = dayOfWeek === 0 ? 0 : -dayOfWeek;
      const firstSunday = new Date(date);
      firstSunday.setDate(date.getDate() + diffDays);

      // 计算目标周的起始日期
      const weekStart = new Date(firstSunday);
      weekStart.setDate(firstSunday.getDate() + (week - 1) * 7);

      // 计算结束日期（周六）
      const weekEnd = new Date(weekStart);
      weekEnd.setDate(weekStart.getDate() + 6);

      // 格式化日期为yyyy-mm-dd
      const format = (d) =>
        [
          d.getFullYear(),
          (d.getMonth() + 1).toString().padStart(2, "0"),
          d.getDate().toString().padStart(2, "0"),
        ].join("-");

      return {
        start: format(weekStart),
        end: format(weekEnd),
      };
    },

    handleEndChangeYear(val) {
      this.dateRange.end = val;
    },
    handleStartChangeYear(val) {
      this.dateRange.start = val;
    },
    handleEndChange() {},
    changeQuarter(val) {
      console.log(val);

      this.dateRange.start = val;
      this.dateRange.end = val;
      // this.dateRange = this.getQuarterDateRange(new Date().getFullYear(), val);
    },
    changeWeek(val) {
      this.dateRange = this.getWeekDateRange(new Date().getFullYear(), val);
    },
    // 生成年份数组（示例生成2020-2030）
    generateYears(start, end) {
      return Array.from({ length: end - start + 1 }, (_, i) => start + i);
    },

    // 生成季度配置
    generateQuarters() {
      return [
        { label: "2025", value: 2025, months: [1, 2, 3] },
        { label: "2024", value: 2024, months: [4, 5, 6] },
        { label: "2023", value: 2023, months: [7, 8, 9] },
        { label: "2022", value: 2022, months: [10, 11, 12] },
      ];
    },

    // 生成周数据（基于ISO周算法）
    generateWeeks(year) {
      const weeks = [];
      let date = new Date(year, 0, 1);

      // 找到第一个周四（ISO周起始判断依据）
      while (date.getDay() !== 4) {
        date.setDate(date.getDate() + 1);
      }

      // 生成全年周数据
      for (let weekNum = 1; weekNum <= 52; weekNum++) {
        const weekStart = new Date(date);
        const weekEnd = new Date(date);
        weekEnd.setDate(weekEnd.getDate() + 6);

        weeks.push({
          number: weekNum,
          start: weekStart,
          end: weekEnd,
          value: weekNum,
          label: `第${weekNum}周`,
        });

        date.setDate(date.getDate() + 7);
      }

      return weeks;
    },

    // 处理类型切换
    handleTypeChange() {
      if (this.timeType === "year") {

        console.log(123);

        this.startYear = new Date().toISOString().split("T")[0];
        this.endYear = new Date().toISOString().split("T")[0];
        this.dateRange.start = new Date().getFullYear();
        this.dateRange.end = new Date().getFullYear();
        this.dateRange.type = 1;
        this.$emit("changeTime", { ...this.dateRange, type:1 });
      } else if (this.timeType === "month") {
        this.dateRange.start = this.defaultMonthRange[0];
        this.dateRange.end = this.defaultMonthRange[1];
        this.dateRange.type = 3;
        this.$emit("changeTime", { ...this.dateRange, type:3 });

      } else if (this.timeType === "quarter") {
        console.log(456)
        // this.dateRange = this.getQuarterDateRange(new Date().getFullYear(), 1);
        this.dateRange.start = new Date().getFullYear();
        this.dateRange.end = new Date().getFullYear();
        this.selectedValue1 = new Date().toISOString().split("T")[0];
        this.dateRange.type = 2;
        this.$emit("changeTime", { ...this.dateRange, type:2 });
      } else if (this.timeType === "week") {
        this.selectedValue2 = 1;
        this.dateRange = this.getWeekDateRange(new Date().getFullYear(), 1);
      }
    },
    // 日期格式化
    formatDate(date) {
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}`;
    },
  },
};
</script>

<style>
.date-selector {
  display: flex;
  max-width: none !important;
  margin: 0 !important;
  padding: 0 !important;
  border: none !important;
}
.select-group {
  margin: 10px 0;
}
select {
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #ccc;
  margin-left: 10px;
}
.date-range {
  margin-top: 15px;
  padding: 10px;
  color: #fff;
  /* background-color:p; */
  border-radius: 4px;
}
:deep(.el-select-dropdown__item.selected) {
  color: #ccc !important;
}
</style>
